//
//  HomeController.swift
//  Unzip
//
//  Created by zhibao on 2024/2/1.
//

import UIKit
import SnapKit
import QuickLook
import SSZipArchive

@objc class HomeController:SuperController,UITableViewDelegate,UITableViewDataSource,DataChangeDelegate,UIDocumentInteractionControllerDelegate,UIDocumentPickerDelegate,TZImagePickerControllerDelegate{
    var docum = IMPORTAUDIOSTYPE
    fileprivate var dataArray = [String]()
    fileprivate var showTableView:MYTableView!
    fileprivate var document:UIDocumentInteractionController!
    fileprivate var yulanPath = ""
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if UserDefaults.standard.value(forKey: "privacy1") == nil {
            Helper.privacyAgreementShow()
        }
        self.getListData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getPayInfo()
        self.gk_navTitle = LocalizedString("文件列表");
        let userBtn = UIButton(type: .custom)
        userBtn.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
        userBtn.tag = 100
        userBtn.setImage(Helper.image(with: UIColor.white, with: UIImage(named: "bar_3")), for: .normal)
        userBtn.tintColor = UIColor.white
        userBtn.titleLabel?.font = MY_SCALE_BoldFont(15)
        userBtn.setTitleColor(UIColor.white, for: .normal)
        userBtn.addTarget(self, action: #selector(navBtnClick(sender: )), for: .touchUpInside)
        let leftItem = UIBarButtonItem(customView: userBtn)
        self.gk_navLeftBarButtonItem = leftItem
        
        let shuoBtn = UIButton(type: .custom)
        shuoBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 40)
        shuoBtn.tag = 101
        shuoBtn.tintColor = UIColor.white
        shuoBtn.titleLabel?.font = MY_SCALE_BoldFont(12)
        shuoBtn.setTitleColor(UIColor.white, for: .normal)
        shuoBtn.setImage(UIImage(systemName: "list.bullet.rectangle.portrait.fill"), for: .normal)
        shuoBtn.addTarget(self, action: #selector(navBtnClick(sender: )), for: .touchUpInside)
        let item = UIBarButtonItem(customView: shuoBtn)
        self.gk_navRightBarButtonItem = item
        
        self.initTableView()
        
        let addBtn = UIButton(type: .custom)
        addBtn.setTitle("+", for: .normal)
        addBtn.setTitleColor(UIColor.white, for: .normal)
        addBtn.titleLabel?.font = MY_SCALE_BoldFont(20)
        addBtn.backgroundColor = MYBlue
        addBtn.layer.cornerRadius = pixw(p: 20);
        addBtn.addTarget(self, action: #selector(addClick), for: .touchUpInside)
        self.view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.bottom.equalTo(self.showTableView).offset(pixw(p: -80))
            make.width.height.equalTo(pixw(p: 40))
        }
    }
    
    fileprivate func getPayInfo(){
        if IAPShare.sharedHelper().iap == nil {
            let dataSet = NSSet(array: ["com.jieyaya.zhou","com.jieyaya.yue","com.jieyaya.ji","com.jieyaya.year"])
            IAPShare.sharedHelper().iap = IAPHelper(productIdentifiers: dataSet as? Set<AnyHashable>)
        }
        IAPShare.sharedHelper().iap.requestProducts { request, response in
            DLog(message: "response1==\(String(describing: response?.products))")
        }
        IAPShare.sharedHelper().iap.production = false
    }
    
    @objc fileprivate func navBtnClick(sender:UIButton){
        if sender.tag == 100 {
            //导航左侧按钮被点击
            let controller = MeController()
            self.navigationController?.pushViewController(controller, animated: true)
        }else if sender.tag == 101 {
            //导航右侧按钮被点击
            let controller = TipController()
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    func initTableView() {
        showTableView = MYTableView(frame: CGRectMake(0, navigationFullHeight(), SCREEN_WIDTH, SCREEN_HEIGHT - navigationFullHeight() - tabBarFullHeight()), style: .plain)
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.dataChangeDelegate = self
        showTableView.separatorStyle = .none
        showTableView.register(HomeCell.self, forCellReuseIdentifier: "HomeCell")
        self.view.addSubview(showTableView)
        showTableView.noDataType = .TableViewNoDataType_FILE
        showTableView.mj_footer?.endRefreshingWithNoMoreData()
    }
    
    func getListData(){
        let tempData = try? Helper.contentsOfDirectory(atPath: docum)
        if tempData != nil {
            dataArray = tempData!
            DLog(message: "dataArray === \(dataArray)")
            self.showTableView.reloadData()
        }
    }
    
    @objc func addClick() {
        Helper.alertAddToApp { index in
            if index == 1000 {
                Helper.alertShow(withTitle: LocalizedString("新建"), withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { anwer in
                    if (anwer ?? "").qmui_trimAllWhiteSpace.count > 0 {
                        Helper.createDir(Helper.getPath()! + "/" + self.docum + "/" + (anwer ?? "").qmui_trimAllWhiteSpace)
                        QMUITips.showSucceed(LocalizedString("创建成功！"))
                        self.getListData()
                    }
                }
            }else if index == 1001 {
                let documentType = ["public.item",
                ]
                let documentPicker = UIDocumentPickerViewController(documentTypes: documentType, in: .open)
                documentPicker.delegate = self
                documentPicker.allowsMultipleSelection = false
                documentPicker.modalPresentationStyle = .fullScreen
                self.navigationController?.present(documentPicker, animated: true, completion: {
                    
                })
            }else if index == 1002 {
                
                let imagePickerVc = TZImagePickerController(maxImagesCount: 9, delegate: self)
                imagePickerVc?.naviTitleColor = UIColor.white
                imagePickerVc?.barItemTextColor = UIColor.white
                imagePickerVc?.statusBarStyle = .lightContent
                imagePickerVc?.allowPickingVideo = true
                imagePickerVc?.allowTakeVideo = true
                imagePickerVc?.allowTakePicture = true
                imagePickerVc?.allowPickingImage = true
                imagePickerVc?.allowPickingMultipleVideo = false
                imagePickerVc?.allowEditVideo = true
                imagePickerVc?.allowPickingOriginalPhoto = true
                imagePickerVc?.didFinishPickingAndEditingVideoHandle = {
                    coverImage,outputPath,errorMsg in
                    DLog(message: "\(String(describing: outputPath))")
                    let tempArray = outputPath?.components(separatedBy: "/")
                    Helper.saveData([outputPath ?? "",tempArray?.last ?? ""], withDocum: self.docum, withType: DOCUMENTYPE)
                    QMUITips.showSucceed(LocalizedString("导入成功"), detailText: LocalizedString("请刷新查看"))
                    self.getListData()
                }
                imagePickerVc?.didFinishPickingPhotosHandle = {
                    photos,assets,flag in
                    
                    guard let imgs = photos else {
                            return
                        }
                    for img in  imgs{
                        let imgData = img.pngData()
                        let filePath = Helper.getPath()! + "/" + self.docum + "/" + "myPic\(Helper.getRandStr(4) ?? "lujing").png"
                        Helper.createDir(Helper.getPath()! + "/" + self.docum)
                        do {
                            try? imgData!.write(to: URL(fileURLWithPath: filePath), options: .atomic)
                               print("Image saved successfully to \(filePath)")
                            QMUITips.showSucceed(LocalizedString("导入成功"), detailText: LocalizedString("请刷新查看"))
                            self.getListData()
                           } catch {
                               print("Failed to save image to file: \(error)")
                               QMUITips.showSucceed(LocalizedString("导入失败"), detailText: LocalizedString("请稍后再试"))
                           }
                    }
                }
                imagePickerVc!.modalPresentationStyle = .fullScreen
                self.navigationController?.present(imagePickerVc!, animated: true, completion: {
                    
                })
            }else if index == 1003 {
                let controller = ImportTipController()
                controller.index = 1
                self.navigationController?.pushViewController(controller, animated: true)
            }else if index == 1004 {
                let controller = ImportTipController()
                controller.index = 2
                self.navigationController?.pushViewController(controller, animated: true)
            }else if index == 1005 {
                let controller = ImportWIFIController()
                self.navigationController?.pushViewController(controller, animated: true)
            }
        }
    }
}

extension HomeController {
    func refreshData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    
    func loadMoreData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let nameUrl = dataArray[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeCell
        cell.updata(name: nameUrl,docum: self.docum, flag: false)
        cell.doneBlock = {
            let nameArray = nameUrl.components(separatedBy: ".")
            self.dealAudio(nameUrl: nameUrl)
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let name = dataArray[indexPath.row]
        let nameArray = name.components(separatedBy: ".")
        if nameArray.count < 2 {
            let subController = SubHomeController()
            subController.docum = "\(self.docum)/\(name)"
            subController.navTitle = name
            self.navigationController?.pushViewController(subController, animated: true)
        }else{
            let lastUrl = "\(self.docum)/\(name)"
            let path = Helper.getPath()! + "/" + lastUrl
            
            yulanPath = path
            document = UIDocumentInteractionController(url:URL(fileURLWithPath: path))
            document.delegate = self
            document.presentPreview(animated: true)
        }
        
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let name = dataArray[indexPath.row]
        let nameArray = name.components(separatedBy: ".")
        let reNameAction = UIContextualAction(style: .normal, title: LocalizedString("重命名")) { (action, view, completed)  -> Void in
            let flag = MYGlobal.share().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去看看解锁该功能！"), withSureBtnTitle: LocalizedString("去看看"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            Helper.alertShow(withTitle: LocalizedString("重命名"), withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { newName in
                if (newName!.qmui_trimAllWhiteSpace.count > 0){
                    for temName in self.dataArray {
                        let temNameArray = temName.components(separatedBy: ".")
                        if temNameArray.first == newName!.qmui_trimAllWhiteSpace {
                            QMUITips.showError(LocalizedString("提示"), detailText: LocalizedString("名称重复"))
                            return
                        }
                    }
                    Helper.rename(withUrl: name, withNewName: newName!.qmui_trimAllWhiteSpace , withDocum: self.docum, withType: DOCUMENTYPE)
                    self.getListData()
                }
            }
        }
        reNameAction.backgroundColor = MYColor.color(withHexString: "#1AB8A6")
        
        let deleteAction = UIContextualAction(style: .normal, title: LocalizedString("删除")) { (action, view, completed)  -> Void in
            let flag = MYGlobal.share().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去看看解锁该功能！"), withSureBtnTitle: LocalizedString("去看看"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            Helper.alertShow(withTitle: LocalizedString("是否删除？"), withContent: "", withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { selectIndex in
                if(selectIndex == 1){
                    let lastUrl = "\(self.docum)/\(name)"
                    let path = Helper.getPath()! + "/" + lastUrl
                    try? FileManager.default.removeItem(atPath: path)
                }
                self.getListData()
            }
        }
        deleteAction.backgroundColor = MYColor.color(withHexString: "#FC2F55")
        
        let shareAction = UIContextualAction(style: .normal, title: LocalizedString("分享")) { (action, view, completed)  -> Void in
            let flag = MYGlobal.share().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去看看解锁该功能！"), withSureBtnTitle: LocalizedString("去看看"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            //分享
            let lastUrl = self.docum +  "/" + name
            let path = Helper.getPath()! + "/" + lastUrl
            self.showTableView.reloadData()
            self.shareFile(path: path, lastUrl: lastUrl)
        }
        shareAction.backgroundColor = MYBlue
        
        var config = UISwipeActionsConfiguration(actions: [shareAction,deleteAction,reNameAction])
        if nameArray.count < 2 {
            config = UISwipeActionsConfiguration(actions: [reNameAction])
        }
        config.performsFirstActionWithFullSwipe = false
        return config
    }
    
    fileprivate func shareFile(path:String,lastUrl:String){
        self.showTableView.reloadData()
        document = UIDocumentInteractionController(url:URL(fileURLWithPath: path))
        document.delegate = self
        let _ = self.document.presentOptionsMenu(from: self.view.bounds, in: self.view, animated: true)
    }
    
    func dealAudio(nameUrl:String) {
        let bgView = UIView(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
        bgView.backgroundColor = MYColor.color(withHexString: "#010811", alpha: 0.6)
        UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(bgView)
        
        let btnWidth = (SCREEN_WIDTH - pixw(p: 30) - pixw(p: 30)) / 3
        let contentView = UIView(frame: CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, pixw(p: 549)))
        contentView.backgroundColor = MYColor.color(withHexString: "f9f9f9")
        contentView.layer.cornerRadius = pixw(p: 15)
        bgView.addSubview(contentView)
        
        let topCancalBtn = UIButton(type: .custom)
        topCancalBtn.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - contentView.height + pixw(p: 15))
        bgView.addSubview(topCancalBtn)
        topCancalBtn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
            UIView.animate(withDuration: 0.3) {
                contentView.top = SCREEN_HEIGHT
            } completion: { finish in
                
                bgView.removeFromSuperview()
            }
        }))
        
        let cancelBtn = UIButton(type: .custom)
        cancelBtn.setImage(UIImage(named: "pay_quxiao"), for: .normal)
        contentView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.top.equalTo(pixw(p: 15))
            make.right.equalTo(contentView).offset(pixw(p: -15))
            make.width.height.equalTo(pixw(p: 23))
        }
        cancelBtn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
            UIView.animate(withDuration: 0.3) {
                contentView.top = SCREEN_HEIGHT
            } completion: { finish in
              
                bgView.removeFromSuperview()
            }
        }))
        
        let iconImgView = UIImageView(image: UIImage(named: "com_icon"))
        contentView.addSubview(iconImgView)
        iconImgView.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 15))
            make.top.equalTo(pixw(p: 22))
            make.width.height.equalTo(pixw(p: 37))
        }
        
        let nameLabel = UILabel()
        nameLabel.text = nameUrl
        nameLabel.font = MY_SCALE_RegularFONT(14)
        nameLabel.textColor = MYBlock
        nameLabel.lineBreakMode = .byTruncatingMiddle
        contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImgView.snp.right).offset(pixw(p: 10))
            make.top.equalTo(pixw(p: 21))
            make.right.equalTo(cancelBtn.snp.left).offset(pixw(p: -15))
        }
        
        let sizeAndtimeLabel = UILabel()
        sizeAndtimeLabel.font = MY_SCALE_RegularFONT(11)
        sizeAndtimeLabel.textColor = MYColor.color(withHexString: "999999")
        sizeAndtimeLabel.lineBreakMode = .byTruncatingMiddle
        contentView.addSubview(sizeAndtimeLabel)
        sizeAndtimeLabel.snp.makeConstraints { make in
            make.left.right.equalTo(nameLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(pixw(p: 3))
        }
        
        let path = (Helper.getPath() ?? "") + "/" + self.docum + "/" + nameUrl
        let fileManager = FileManager.default
        do {
            let attributes = try fileManager.attributesOfItem(atPath:path)
            
            // 从属性字典中获取文件大小
            if let fileSizeNumber = attributes[.size] as? UInt64 {
                let mSize:Float = Float(fileSizeNumber) / 1024 / 1024
                let kSize:Float = Float(fileSizeNumber) / 1024
                var sizeStr = NSString(format: "%.2fK",kSize)
                if mSize > 1 {
                    sizeStr = NSString(format: "%.2fM",mSize)
                }
                
                sizeAndtimeLabel.text = "\(sizeStr)"
                let time = Helper.getFileDuratiomn(path)
                if time != "00:00:00" {
                    sizeAndtimeLabel.text = "\(sizeStr)   \(time ?? "00:00:00")"
                }
            }
            
        } catch {
            // 处理错误，例如文件不存在或无法读取属性
            print("Error retrieving folder attributes")
        }
        
        UIView.animate(withDuration: 0.3) {
            contentView.top = SCREEN_HEIGHT - contentView.height + pixw(p: 15)
        }
        let showContents = [
            "zip","rar","7z"
        ]
        
        //是否为压缩文件
        var yaFlag = false
        let nameArray = nameUrl.components(separatedBy: ".") 
        if showContents.contains(nameArray.last ?? ""){
            yaFlag = true
        }
        let cysLabel = UILabel(frame: CGRectMake(pixw(p: 15), pixw(p: 85), SCREEN_WIDTH - pixw(p: 30), pixw(p: 20)))
        cysLabel.text = LocalizedString("选择压缩类型")
        if yaFlag {
            cysLabel.text = LocalizedString("当前压缩类型")
        }
        cysLabel.font = MY_SCALE_HeavyFONT(16)
        cysLabel.textColor = MYBlock
        contentView.addSubview(cysLabel)
        
        var tempTop = cysLabel.bottom
        
        
        var zipArray = [UIButton]()
        tempTop = tempTop + pixw(p: 10)
        var selectIndex = 0
        for i in 0 ..< showContents.count {
            let btn = UIButton(type: .custom)
            btn.frame = CGRectMake(pixw(p: 15) + (btnWidth +  pixw(p: 15)) * CGFloat(i), tempTop, btnWidth, pixw(p: 40))
            btn.backgroundColor = MYColor.color(withHexString: "f1f1f1")
            btn.layer.cornerRadius = pixw(p: 10)
            contentView.addSubview(btn)
            btn.tag = 1000 + i
            zipArray.append(btn)
            btn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
                for tempBtn in zipArray {
                    tempBtn.backgroundColor = MYColor.color(withHexString: "f1f1f1")
                    tempBtn.setTitleColor(MYColor.color(withHexString: "888888"), for: .normal)
                }
                btn.backgroundColor = MYBlue
                btn.setTitleColor(UIColor.white, for: .normal)
                selectIndex = btn.tag - 1000
                
            }))
            if yaFlag {
                btn.isUserInteractionEnabled = false
                if showContents[i] == nameArray.last {
                    btn.backgroundColor = MYBlue
                    btn.setTitleColor(UIColor.white, for: .normal)
                }else{
                    btn.backgroundColor = .clear
                    btn.setTitleColor(UIColor.clear, for: .normal)
                }
            }else{
                if i == 0 {
                    btn.backgroundColor = MYBlue
                    btn.setTitleColor(UIColor.white, for: .normal)
                }else{
                    btn.backgroundColor = MYColor.color(withHexString: "f1f1f1")
                    btn.setTitleColor(MYColor.color(withHexString: "888888"), for: .normal)
                }
            }
            
            btn.setTitle(showContents[i], for: .normal)
            btn.titleLabel?.font = MY_SCALE_RegularFONT(13)
            if i == showContents.count - 1 {
                tempTop = btn.bottom + pixw(p: 30)
            }
        }
        
        let cpwLabel = UILabel(frame: CGRectMake(pixw(p: 15), tempTop, SCREEN_WIDTH - pixw(p: 30), pixw(p: 20)))
        cpwLabel.text = LocalizedString("请输入密码")
        cpwLabel.font = MY_SCALE_HeavyFONT(16)
        cpwLabel.textColor = MYBlock
        contentView.addSubview(cpwLabel)
        
        tempTop = cpwLabel.bottom + pixw(p: 7)
        let pwField = QMUITextField(frame: CGRectMake(pixw(p: 15), tempTop, SCREEN_WIDTH - pixw(p: 100), pixw(p: 40)))
        pwField.backgroundColor = MYColor.color(withHexString: "f1f1f1")
        pwField.layer.cornerRadius = pixw(p: 4)
        pwField.placeholder = LocalizedString("压缩密码(选填)")
        if yaFlag {
            pwField.placeholder = LocalizedString("解压密码(选填)")
        }
        pwField.textInsets = UIEdgeInsets(top: 0, left: pixw(p: 10), bottom: 0, right: 0)
        pwField.font = MY_SCALE_RegularFONT(13)
        contentView.addSubview(pwField)
        tempTop = pwField.bottom + pixw(p: 30)
        
        let dealBtn = UIButton(type: .custom)
        dealBtn.frame = CGRectMake(0, tempTop, pixw(p: 200), pixw(p: 55))
        dealBtn.centerX = (SCREEN_WIDTH - pixw(p: 30)) / 2
        dealBtn.backgroundColor = MYRed
        dealBtn.layer.cornerRadius = pixw(p: 20)
        contentView.addSubview(dealBtn)
        dealBtn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
            
            let flag = MYGlobal.share().isVip()
            if(flag == false){
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去看看解锁该功能！"), withSureBtnTitle: LocalizedString("去看看"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        UIView.animate(withDuration: 0.3) {
                            contentView.top = SCREEN_HEIGHT
                        } completion: { finish in
                           
                            bgView.removeFromSuperview()
                            let controller = PayMarkController()
                            self.navigationController?.pushViewController(controller, animated: true)
                        }
                    }
                }
                return
            }
            
            //DLog(message: "selectindex==\(selectIndex)")
            //原始地址
            let fomUrl = "\(self.docum)/\(nameUrl)"
            let formPath = Helper.getPath()! + "/" + fomUrl
            
            //目标地址
            let toName = Helper.getSameNum(nameArray.first! +  "." + showContents[selectIndex], withDoum: self.docum)
            let toUrl = "\(self.docum)/\(String(describing: toName!))"
            let toPath = Helper.getPath()! + "/" + toUrl
            Helper.createDir(toPath)
            
            let pw = (pwField.text ?? "").qmui_trimAllWhiteSpace.count > 0 ? pwField.text!.qmui_trimAllWhiteSpace : nil
            
            var success = false
            if yaFlag {
                success = MyUnArchive.unarchive(from: formPath, toPath: Helper.getPath()! + "/" + self.docum, password: pw)
                
            }else{
                success = SSZipArchive.createZipFile(atPath: toPath, withFilesAtPaths: [formPath], withPassword: pw)
            }
            
            
            if success {
                print("Success zip")
                //Helper.saveData([toPath ,toName ?? ""], withDocum: IMPORTAUDIOSTYPE , withType: DOCUMENTYPE)
                if yaFlag {
                    QMUITips.showSucceed(LocalizedString("解压成功"), detailText: LocalizedString("在当前列表查看"))
                }else{
                    QMUITips.showSucceed(LocalizedString("压缩成功"), detailText: LocalizedString("在当前列表查看"))
                }
               
                bgView.removeFromSuperview()
                
                Helper.deleUrl(nameUrl, withDocum: self.docum, withType: DOCUMENTYPE)
                self.getListData()
            } else {
                if yaFlag {
                    QMUITips.showSucceed(LocalizedString("解压失败"), detailText: LocalizedString("请输入密码或格式非zip/rar/7z"))
                }else{
                    QMUITips.showSucceed(LocalizedString("压缩失败"), detailText: LocalizedString("请输入密码或稍后再试"))
                }
            }
            
        }))
        dealBtn.setTitle(LocalizedString("开始压缩"), for: .normal)
        if yaFlag {
            dealBtn.setTitle(LocalizedString("开始解压"), for: .normal)
        }
        dealBtn.titleLabel?.font = MY_SCALE_BoldFont(13)
        dealBtn.setTitleColor(UIColor.white, for: .normal)
        tempTop = dealBtn.bottom + pixw(p: 40)
        
        let cotherLabel = UILabel(frame: CGRectMake(pixw(p: 15), tempTop, SCREEN_WIDTH - pixw(p: 30), pixw(p: 20)))
        cotherLabel.text = LocalizedString("其他功能")
        cotherLabel.font = MY_SCALE_HeavyFONT(16)
        cotherLabel.textColor = MYBlock
        contentView.addSubview(cotherLabel)
        tempTop = tempTop + pixw(p: 20)
        tempTop = tempTop + pixw(p: 10)
        
        let otherContents = [
            [
                "title":LocalizedString("分享"),"img":"square.and.arrow.up"
            ],
            [
                "title":LocalizedString("重命名"),"img":"pencil"
            ],
            [
                "title":LocalizedString("删除"),"img":"trash"
            ]
        ]
        
        for i in 0 ..< otherContents.count {
            let btn = UIButton(type: .custom)
            btn.frame = CGRectMake(pixw(p: 15) + (btnWidth +  pixw(p: 15)) * CGFloat(i), tempTop, btnWidth, pixw(p: 75))
            btn.backgroundColor = MYColor.color(withHexString: "f1f1f1")
            btn.layer.cornerRadius = pixw(p: 10)
            contentView.addSubview(btn)
            btn.tag = 1000 + i
            btn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
                let flag = MYGlobal.share().isVip()
                if(flag == false){
                    Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去看看解锁该功能！"), withSureBtnTitle: LocalizedString("去看看"), withCancelBtnTitle: LocalizedString("取消")) { index in
                        //去往购买中心
                        if index == 1 {
                            UIView.animate(withDuration: 0.3) {
                                contentView.top = SCREEN_HEIGHT
                            } completion: { finish in
                               
                                bgView.removeFromSuperview()
                                let controller = PayMarkController()
                                self.navigationController?.pushViewController(controller, animated: true)
                            }
                        }
                    }
                }else{
                    UIView.animate(withDuration: 0.3) {
                        contentView.top = SCREEN_HEIGHT
                        
                        
                    } completion: { finish in
                        bgView.removeFromSuperview()
                        if btn.tag == 1000 {
                            //分享
                            let lastUrl = "\(self.docum)/\(nameUrl)"
                            let path = Helper.getPath()! + "/" + lastUrl
                            self.shareFile(path: path, lastUrl: lastUrl)
                        }else if btn.tag == 1002 {
                            //删除
                            Helper.alertShow(withTitle: LocalizedString("是否删除？"), withContent: "", withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { selectIndex in
                                if(selectIndex == 1){
                                    let lastUrl = "\(self.docum)/\(nameUrl)"
                                    let path = Helper.getPath()! + "/" + lastUrl
                                    try? FileManager.default.removeItem(atPath: path)
                                }
                                self.getListData()
                            }
                        }else if btn.tag == 1001 {
                            //重命名
                            Helper.alertShow(withTitle: LocalizedString("重命名"), withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { newName in
                                if (newName!.qmui_trimAllWhiteSpace.count > 0){
                                    for tempName in self.dataArray {
                                        let nameArray = tempName.components(separatedBy: ".")
                                        if newName!.qmui_trimAllWhiteSpace == nameArray.first {
                                            QMUITips.showError(LocalizedString("提示"), detailText: LocalizedString("名称重复"))
                                            return
                                        }
                                    }
                                    Helper.rename(withUrl: nameUrl, withNewName: newName!.qmui_trimAllWhiteSpace , withDocum: self.docum, withType: DOCUMENTYPE)
                                    self.getListData()
                                }
                            }
                        }
                        
                    }
                }
            }))
            btn.setImage(UIImage(systemName: otherContents[i]["img"]!), for: .normal)
            btn.tintColor = MYBlue
            btn.setTitleColor(MYBlock, for: .normal)
            btn.setTitle(otherContents[i]["title"]!, for: .normal)
            btn.titleLabel?.font = MY_SCALE_RegularFONT(15)
            btn.setButtonImageAlignmentStyle(.top, imageAndLabelSpace: 8)
        }
    }
}

extension HomeController{
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        DLog(message: "urls==\(urls)")
        if urls.count < 1{
            return
        }
        
        for url in urls {
            let flag =  url.startAccessingSecurityScopedResource()
            if(flag){
                let fileName = url.lastPathComponent
                Helper.saveData([url,fileName], withDocum: self.docum, withType: DOCUMENTYPE)
                QMUITips.showSucceed(LocalizedString("导入成功"), detailText: LocalizedString("请刷新查看"))
            }else{
                QMUITips.showSucceed(LocalizedString("导入失败"), detailText: LocalizedString("请稍后再试"))
            }
            url.stopAccessingSecurityScopedResource()
        }
        self.getListData()
    }
    
    
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
         return self
    }
    
    func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
        return self.view
    }
    
    func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
        return self.view.frame
    }
    
    func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
        DLog(message: "disMiss")
    }
}


